import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:qunaimedical/components/custom_avatar.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_option.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/qa_user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/field_edit.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_util.dart';
import 'package:qunaimedical/utils/log_util.dart';

import '../values/urls.dart';

/// 个人信息界面
class ProfilePage extends StatefulWidget {
  static const String routeName = '/profile';

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  static String _tag = '_ProfilePageState';

  @override
  Widget build(BuildContext context) {
    QAUser user = context.watch<StoreInfo>().qaUser!;
    return Scaffold(
      appBar: AppBar(title: Text('个人账号')),
      body: ListView(
        children: [
          CustomDivider(),
          ItemOption(
            height: 100,
            text: '头像',
            trailing: CustomAvatar(
              size: 70,
              avatarUrl: user.photo,
              margin: EdgeInsets.only(right: 10),
            ),
            onTap: _selectAvatar,
          ),
          ItemOption(
            text: '姓名',
            secondText: user.name,
            onTap: () => _goToEditAndUpdate(FieldEditType.name),
          ),
          ItemOption(
            text: '医院名称',
            secondText: user.companyId,
            onTap: () => _goToEditAndUpdate(FieldEditType.hospital),
          ),
          ItemOption(
            text: '科室',
            secondText: user.officeId,
            onTap: () => _goToEditAndUpdate(FieldEditType.department),
          ),
          ItemOption(
            text: '职称',
            secondText: user.level,
            onTap: () => _goToEditAndUpdate(FieldEditType.position),
          ),
          ItemOption(
            text: '擅长领域',
            secondText: user.major,
            onTap: () => _goToEditAndUpdate(FieldEditType.skill),
          ),
          ItemOption(
            text: '基本简历',
            secondText: user.resume,
            onTap: () => _goToEditAndUpdate(FieldEditType.resume),
          ),
          ItemOption(
            text: '手机号',
            secondText: user.phone,
            hideRightArrow: true,
          ),
        ],
      ),
    );
  }

  void _goToEditAndUpdate(FieldEditType editType) {
    QAUser user = context.read<StoreInfo>().qaUser!;
    String oldValue = "";
    switch (editType) {
      case FieldEditType.name:
        oldValue = user.name;
        break;
      case FieldEditType.hospital:
        oldValue = user.companyId;
        break;
      case FieldEditType.department:
        oldValue = user.officeId;
        break;
      case FieldEditType.position:
        oldValue = user.level;
        break;
      case FieldEditType.skill:
        oldValue = user.major;
        break;
      case FieldEditType.resume:
        oldValue = user.resume;
        break;
      default:
    }
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (c) => FieldEditPage(
          type: editType,
          value: oldValue,
        ),
      ),
    ).then((value) {
      Log.d(_tag, value);
      if (value != null) {
        switch (editType) {
          case FieldEditType.name:
            _update(name: value);
            break;
          case FieldEditType.hospital:
            _update(hospital: value);
            break;
          case FieldEditType.department:
            _update(department: value);
            break;
          case FieldEditType.position:
            _update(position: value);
            break;
          case FieldEditType.skill:
            _update(skill: value);
            break;
          case FieldEditType.resume:
            _update(resume: value);
            break;
          default:
        }
      }
    });
  }

  void _selectAvatar() {
    showDialog(
        context: context,
        builder: (c) {
          return SimpleDialog(
            title: Text('更换头像'),
            children: [
              SimpleDialogOption(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Text('从相册选取'),
                ),
                onPressed: () => _selectImage(ImageSource.gallery),
              ),
              SimpleDialogOption(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Text('使用相机拍摄'),
                ),
                onPressed: () => _selectImage(ImageSource.camera),
              ),
            ],
          );
        });
  }

  final _picker = ImagePicker();

  /// 选中的图片
  XFile? _image;

  void _selectImage(ImageSource source) async {
    Navigator.pop(context);
    PermissionStatus status = await Permission.camera.request();
    Log.d(_tag, "camera status:$status");
    if (source == ImageSource.gallery || status == PermissionStatus.granted) {
      var data = await _picker.pickImage(source: source);
      if (data != null) {
        _image = data;
        _uploadImages();
      }
    }
    if (source == ImageSource.camera &&
        status == PermissionStatus.permanentlyDenied) {
      DialogUtil.showAlertDialog(context, "您需要授予相机权限才可以进行拍照。", onPressed: () {
        Navigator.pop(context);
        openAppSettings();
      });
    }
  }

  /// 图片上传
  void _uploadImages() async {
    try {
      DialogUtil.showWaitDialog(context);
      QAUser user = context.read<StoreInfo>().qaUser!;
      FormData formData = FormData.fromMap({"id": user.id});
      formData.files.addAll((await CommonUtil.files2MapEntry([_image])));
      Response response = await XHttp.instance.post(
        Urls.UPLOAD_IMAGE,
        data: formData,
      );
      if (mounted) {
        Navigator.pop(context);
        if (response.statusCode == 200 && response.data["code"] == 1) {
          String avatarUrl = response.data["data"]["url"];
          user.photo = avatarUrl;
          context.read<StoreInfo>().updateQAUser(user);
        }
      }
    } on DioError catch (e) {
      if (mounted) {
        Navigator.pop(context);
        CommonUtil.catchDioError(e);
      }
    }
  }

  void _update({
    String? name,
    String? hospital,
    String? department,
    String? position,
    String? skill,
    String? resume,
  }) async {
    QAUser user = context.read<StoreInfo>().qaUser!;
    Map<String, dynamic> params = {"id": user.id};
    if (name != null) {
      params["name"] = name;
      user.name = name;
    }
    if (hospital != null) {
      params["companyId"] = hospital;
      user.companyId = hospital;
    }
    if (department != null) {
      params["officeId"] = department;
      user.officeId = department;
    }
    if (position != null) {
      params["level"] = position;
      user.level = position;
    }
    if (skill != null) {
      params["major"] = skill;
      user.major = skill;
    }
    if (resume != null) {
      params["resume"] = resume;
      user.resume = resume;
    }
    try {
      DialogUtil.showWaitDialog(context);
      Response response = await XHttp.instance.post(
        Urls.UPDATE,
        queryParameters: params,
      );
      if (mounted) {
        Navigator.pop(context);
        if (response.statusCode == 200) {
          if (response.data["code"] == 1) {
            // 修改成功
            context.read<StoreInfo>().updateQAUser(user);
          }
        }
      }
    } on DioError catch (e) {
      if (mounted) {
        Navigator.pop(context);
        CommonUtil.catchDioError(e);
      }
    }
  }
}
